package com.base.test.mutual.utils;

import com.alibaba.fastjson.JSON;
import com.base.commons.tools.utils.HttpConnectUtil;
import com.base.commons.tools.utils.StringUtils;
import com.base.test.mutual.dto.CustomerGetTokenReqData;
import com.base.test.mutual.dto.CustomerJwtToken;
import com.base.test.mutual.properties.CustomerProperties;
import lombok.extern.log4j.Log4j2;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;
import java.util.Map;

/**
 * yinbangshan
 */
@Log4j2
@Configuration
@EnableConfigurationProperties(CustomerProperties.class)
public class CustomerHttpUtils {

    @Autowired
    CustomerProperties customerProperties;


    public  <T> T execute(T requestObj, String url, String token, String method, Class<?> clazz){
        url=customerProperties.getUrl()+url;
        HttpHeaders headers = new HttpHeaders();
        if(StringUtils.isNotEmpty(token)){
            headers.add(HttpHeaders.AUTHORIZATION,token);
        }
        headers.add(HttpHeaders.ACCEPT_LANGUAGE,"zh-cn");
        log.info("模块Module:{},url:{},请求参数{}","customer",url,JSON.toJSONString(requestObj));
        ResponseEntity res = HttpConnectUtil.tempHttp(requestObj, url, headers, method, new HashMap<>(), clazz);
        log.info("模块Module:{},url:{},请求结果：{}","customer",url,res.getBody());
        return (T) res.getBody();
    }

    /**
     * 调授权， 获取access token
     * @return
     */
    private Map<String, Object> getSystemAccessToken(String appId,String appKey,String url) {
        CustomerGetTokenReqData reqData=new CustomerGetTokenReqData();
        reqData.setAppId(appId);
        reqData.setAppKey(appKey);
        url = customerProperties.getUrl() + url;
        ResponseEntity responseEntity = HttpConnectUtil.tempHttp(reqData, url,
                null, "post", new HashMap<>(), Map.class);
        Map<String, Object> res = (Map) responseEntity.getBody();
        log.info("模块Module:{},url:{},请求参数[{}],请求结果：{}", "customer", url, JSON.toJSONString(reqData), responseEntity.getBody());
        return (Map<String, Object>) res.get("data");
    }

    /**
     * customer生成系统授权token
     * @return
     */
    public CustomerJwtToken generateSystemToken(String appId,String appKey){
        Map<String, Object> mp = getSystemAccessToken(appId,appKey,customerProperties.getRoutesGetTokenSystem());
        CustomerJwtToken customerJwtToken =new CustomerJwtToken();
        customerJwtToken.setToken("Bearer"+" "+mp.get("access_token").toString());
        customerJwtToken.setExpiration(DateTime.now().plusSeconds(Integer.parseInt(mp.get("expire_in").toString())).toDate());
        return customerJwtToken;
    }
}
